package com.example.ecs.systems;

import com.example.ecs.components.PositionComponent;
import com.example.ecs.components.VelocityComponent;
import com.example.ecs.components.physics.CollisionComponent;
import com.example.ecs.core.Entity;
import com.example.ecs.core.System;

/**
 * CollisionSystem类负责处理实体之间的碰撞检测
 */
public class CollisionSystem extends System {
    @Override
    public void update(double deltaTime) {
        // 检查所有实体对之间的碰撞
        for (int i = 0; i < entities.size(); i++) {
            for (int j = i + 1; j < entities.size(); j++) {
                Entity entityA = entities.get(i);
                Entity entityB = entities.get(j);
                
                if (entityA.hasComponent(PositionComponent.class) &&
                    entityA.hasComponent(CollisionComponent.class) &&
                    entityB.hasComponent(PositionComponent.class) && 
                    entityB.hasComponent(CollisionComponent.class)) {
                    
                    // 检查碰撞
                    if (checkCollision(entityA, entityB)) {
                        // 处理碰撞响应
                        handleCollision(entityA, entityB);
                    }
                }
            }
        }
    }
    
    /**
     * 检查两个实体是否发生碰撞
     */
    private boolean checkCollision(Entity entityA, Entity entityB) {
        PositionComponent posA = entityA.getComponent(PositionComponent.class);
        PositionComponent posB = entityB.getComponent(PositionComponent.class);
        CollisionComponent colA = entityA.getComponent(CollisionComponent.class);
        CollisionComponent colB = entityB.getComponent(CollisionComponent.class);
        
        // 简单的矩形碰撞检测
        boolean collision = posA.x < posB.x + colB.width &&
               posA.x + colA.width > posB.x &&
               posA.y < posB.y + colB.height &&
               posA.y + colA.height > posB.y;
        
        return collision;
    }
    
    /**
     * 处理两个实体之间的碰撞
     */
    private void handleCollision(Entity entityA, Entity entityB) {
        // 如果两个实体都是固体，则简单地分离它们
        if (entityA.getComponent(CollisionComponent.class).solid && 
            entityB.getComponent(CollisionComponent.class).solid) {
            
            PositionComponent posA = entityA.getComponent(PositionComponent.class);
            PositionComponent posB = entityB.getComponent(PositionComponent.class);
            VelocityComponent velA = entityA.getComponent(VelocityComponent.class);
            VelocityComponent velB = entityB.getComponent(VelocityComponent.class);
            
            // 简单的碰撞响应：交换速度
            if (velA != null && velB != null) {
                double tempVx = velA.vx;
                double tempVy = velA.vy;
                velA.vx = velB.vx;
                velA.vy = velB.vy;
                velB.vx = tempVx;
                velB.vy = tempVy;
            }
        }
    }
}